package com.zjitc.backend_shop.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zjitc.backend_shop.mapper.GoodsAlbumMapper;
import com.zjitc.backend_shop.mapper.GoodsMapper;
import com.zjitc.backend_shop.pojo.Goods;
import com.zjitc.backend_shop.pojo.GoodsAlbum;
import com.zjitc.backend_shop.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author 王新瑜
 * @date 2024/12/20 10:05
 */
@Service
@Transactional
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private GoodsAlbumMapper goodsAlbumMapper;

    @Override
    public List<Goods> findAllGoods() {
        return goodsMapper.selectAll();
    }

    @Override
    public Goods addGoods(Goods goods) {
        goodsMapper.insert(goods);
        return goods;
    }

    @Override
    public boolean updateGoods(Goods goods) {
        goodsAlbumMapper.deleteByGoodsId(goods.getId());
        for (GoodsAlbum goodsAlbum : goods.getAlbum()) {
            goodsAlbumMapper.insert(goodsAlbum);
        }
        return goodsMapper.updateByPrimaryKey(goods) > 0;
    }

    @Override
    public boolean deleteGoods(Integer id) {
        return goodsMapper.deleteByPrimaryKey(id) > 0;
    }

    @Override
    public PageInfo<Goods> getGoodsByPage(int pageNum, int pageSize) {
        // 设置分页参数
        PageHelper.startPage(pageNum, pageSize);
        // 执行查询
        List<Goods> goodsList = goodsMapper.selectAll();
        PageInfo<Goods> goodsPageInfo = new PageInfo<>(goodsList);
        return goodsPageInfo;
    }

    @Override
    public Goods findGoodsById(Integer id) {
        return goodsMapper.selectByPrimaryKey(id);
    }
}
